package com.mojito.gorm.executor.impl;

import com.mojito.gorm.datasource.ConnectionManager;
import com.mojito.gorm.map.SqlMapInfo;
import lombok.extern.slf4j.Slf4j;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;

/**
 * @author mojito
 */
@Slf4j
public class StatementHandler {
    private ResultSetHandler resultSetHandler;
    private ParamHandler paramHandler;

    /**
     * 执行操作地层jdbc
     *
     * @param sqlMapInfo
     * @param params
     * @param <T>
     * @return
     */
    public <T> T handle(SqlMapInfo sqlMapInfo, Object[] params) {
        Connection connection = ConnectionManager.getConn();
        PreparedStatement statement = null;

        try {
            statement = connection.prepareStatement(sqlMapInfo.getSql());
            paramHandler.prepareValue(statement, params);
            statement.execute();
            ResultSet resultSet = statement.getResultSet();
            Object setMappings = resultSetHandler.resultSetMapping(sqlMapInfo, resultSet);
            return (T) setMappings;
        } catch (Exception throwable) {
            throwable.printStackTrace();
        }
        return null;
    }

    public void setResultSetHandler(ResultSetHandler resultSetHandler) {
        this.resultSetHandler = resultSetHandler;
    }

    public void setParamHandler(ParamHandler paramHandler) {
        this.paramHandler = paramHandler;
    }
}
